package com.ylyq.ylxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ylyq.ylxx.constants.ExceptionEnum;
import com.ylyq.ylxx.constants.ShiroConstant;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.entity.YlyqUser;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.UserToken;
import com.ylyq.ylxx.model.request.LoginDTO;
import com.ylyq.ylxx.model.response.Result;
import com.ylyq.ylxx.service.IYlyqUserService;
import com.ylyq.ylxx.util.JwtUtils;
import com.ylyq.ylxx.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @Description 用户登录
 */
@Slf4j
@RestController
@RequestMapping("/sysUser")
@Api(description = "登录、用户管理")
public class LoginController {

    @Autowired
    private IYlyqUserService sysUserService;


    /**
     * 登录
     *
     * @Author
     * @CreateTime 2020/2/29 9:21
     */
    @ApiOperation(value = "登录", response = YlyqUser.class)
    @PostMapping("/login")
    public ResponseData login(@Valid @RequestBody LoginDTO loginDTO) {

        if (StringUtils.isBlank(loginDTO.getUsername()))
            return new ResponseData(ResponseData.Result.FAIL.getCode(), "用户名不能为空");
        if (StringUtils.isBlank(loginDTO.getPassword()))
            return new ResponseData(ResponseData.Result.FAIL.getCode(), "密码不能为空");
        if (StringUtils.isBlank(loginDTO.getType()))

            return new ResponseData(ResponseData.Result.FAIL.getCode(), "客户端类型不能为空");


        String username = loginDTO.getUsername().trim();
        String password = loginDTO.getPassword().trim();
        String type = loginDTO.getType().trim();
        password = MD5Utils.encrypt(password);
        QueryWrapper<YlyqUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        YlyqUser sysUser = sysUserService.getOne(wrapper);
        if (sysUser == null) {
            return new ResponseData(ExceptionEnum.FAIL.getCode(), "用户名或密码错误");
        }
        UserToken userToken = new UserToken(sysUser.getId(), sysUser.getUsername());
        String token = "";
        try {
            token = JwtUtils.generateToken(userToken, 24 * 60 * 60 * 1000, ShiroConstant.JWT_PRIVATE_KEY + type);
//            redis.setEx(ShiroConstant.ACCESSTOKEN_KEY_PREFIX + token, userToken, 2 * 60 * 60);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成token失败：{}", e.getMessage());
            return new ResponseData(ResponseData.Result.FAIL.getCode(), "系统繁忙");
        }

        Result result = Result.ok()
                .put("token", token)
                .put("user", sysUser);
        return new ResponseData(ResponseData.Result.USER_LOGIN_SUCCESS, result);
    }

    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public ResponseData register(@ApiParam(value = "用户名", required = true) @RequestParam String username, @ApiParam(value = "密码", required = true) @RequestParam String password) {
        return sysUserService.register(username, password);
    }

    @ApiOperation(value = "获取当前用户信息", response = YlyqUser.class)
    @GetMapping("/getCurrentuserInfo")
    public ResponseData getCurrentuserInfo() {
//        return new ResponseData(ResponseData.Result.SUCCESS, sysUserService.getUserInfo(FilterContextHandler.getUserID()));
        YlyqUser user = sysUserService.getById(FilterContextHandler.getUserID());
        if (user == null)
            return new ResponseData(ResponseData.Result.FAIL);
        return new ResponseData(ResponseData.Result.SUCCESS, user);
    }

    @ApiOperation(value = "根据用户id获取用户信息", response = YlyqUser.class)
    @PostMapping("/getUserInfoById")
    public ResponseData getUserInfoById(@ApiParam(value = "用户id", required = true) @RequestParam String id) {
        if (StringUtils.isBlank(id))
            return new ResponseData(ResponseData.Result.FAIL.getCode(), "用户id不能为空");

//        return new ResponseData(ResponseData.Result.SUCCESS, sysUserService.getUserInfo(FilterContextHandler.getUserID()));
        YlyqUser user = sysUserService.getById(id);
        if (user == null)
            return new ResponseData(ResponseData.Result.FAIL);
        return new ResponseData(ResponseData.Result.SUCCESS, user);
    }

    @ApiOperation(value = "根据用户id删除用户")
    @PostMapping("/deleteUserById")
    public ResponseData deleteUserById(@ApiParam(value = "用户id", required = true) @RequestParam String id) {
        if (StringUtils.isBlank(id))
            return new ResponseData(ResponseData.Result.FAIL.getCode(), "用户id不能为空");

//        return new ResponseData(ResponseData.Result.SUCCESS, sysUserService.getUserInfo(FilterContextHandler.getUserID()));
        boolean user = sysUserService.removeById(id);
        if (!user)
            return new ResponseData(ResponseData.Result.FAIL);
        return new ResponseData(ResponseData.Result.SUCCESS);
    }


    /**
     * 登出
     *
     * @Author JYQ
     * @CreateTime 2020/2/29 9:30
     * @Return Map<String, Object> 返回结果
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public ResponseData getLogout() {
//        menuService.clearCache(FilterContextHandler.getUserID());
        return new ResponseData(ResponseData.Result.SUCCESS);
    }

}
